package com.zys.controller;

import java.util.*;

import java.io.File;
import java.io.OutputStream;
import java.io.FileInputStream;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zys.entity.Result;
import com.zys.service.ReportService;
import com.zys.constant.MessageConstant;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 处理报告相关操作
 */
@RestController
@RequestMapping("/reports")
public class ReportController {

  @Reference
  private ReportService reportService;

  /**
   * 获取报告图表数据(一年内商品的情况)
   *
   * @return Result
   */
  @RequestMapping("/getReport")
  public Result getReport() {
    try {
      Calendar calendar = Calendar.getInstance();   // 获取当前日期
      calendar.add(Calendar.MONTH, -12);     // 往前推 12 个月
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

      List<String> months = new ArrayList<>();
      for (int i = 0; i < 12; i++) {
        calendar.add(Calendar.MONTH, 1);  // 往后推 1 个月
        months.add(simpleDateFormat.format(calendar.getTime()));
      }

      List<Integer> goodsCount = reportService.findGoodsCountByMonth(months);

      Map<String, Object> map = new HashMap<>();
      map.put("months", months);
      map.put("goodsCount", goodsCount);

      return new Result(true, MessageConstant.GET_REPORT_SUCCESS, map);
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.GET_REPORT_FAIL);
    }
  }

  /**
   * 导出 excel 报表
   *
   * @param request  请求对象
   * @param response 响应对象
   * @return Result
   */
  @RequestMapping("/exportBusinessReport")
  public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
    try {
      Map<String, Object> report = reportService.getBusinessReport();
      // 取出返回结果数据, 准备将报表数据写入到 Excel 文件中
      String reportDate = (String) report.get("reportDate");
      Integer todayNewUser = (Integer) report.get("todayNewUser");
      Integer totalUser = (Integer) report.get("totalUser");
      Integer thisWeekNewUser = (Integer) report.get("thisWeekNewUser");
      Integer thisMonthNewUser = (Integer) report.get("thisMonthNewUser");
      Integer todayGoodNumber = (Integer) report.get("todayGoodNumber");
      Integer totalGood = (Integer) report.get("totalGood");
      Integer thisWeekGoodNumber = (Integer) report.get("thisWeekGoodNumber");
      Integer thisMonthGoodNumber = (Integer) report.get("thisMonthGoodNumber");


      // 获取 template 目录的真实路径
      String templatePath = request.getSession().getServletContext()
          .getRealPath("template") + File.separator + "report_template.xlsx";

      // 通过 Apache POI 创建一个操作 excel 表格的对象
      XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(templatePath));
      XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

      XSSFRow row = sheet.getRow(2);                    // 获取第三行
      row.getCell(5).setCellValue(reportDate);          // 日期

      row = sheet.getRow(4);                            // 获取第五行
      row.getCell(5).setCellValue(todayNewUser);        // 本日新增用户数
      row.getCell(7).setCellValue(totalUser);           // 总用户数

      row = sheet.getRow(5);                            // 获取第六行
      row.getCell(5).setCellValue(thisWeekNewUser);     // 本周新增用户数
      row.getCell(7).setCellValue(thisMonthNewUser);    // 本月新增用户数

      row = sheet.getRow(7);                            // 获取第八行
      row.getCell(5).setCellValue(todayGoodNumber);     // 今日新增商品数
      row.getCell(7).setCellValue(totalGood);           // 总商品数

      row = sheet.getRow(8);                            // 获取第九行
      row.getCell(5).setCellValue(thisWeekGoodNumber);  // 本周新增商品数
      row.getCell(7).setCellValue(thisMonthGoodNumber); // 本月新增商品数

      OutputStream out = response.getOutputStream();            // 通过输出流进行文件下载
      response.setContentType("application/vnd.ms-excel");      // 设置 excel 文件格式
      // 设置响应头
      response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
      xssfWorkbook.write(out);                                  // 将 excel 文件输出到客户端

      // 刷新并关闭流
      out.flush();
      out.close();
      xssfWorkbook.close();

      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.GET_REPORT_EXCEL_FAIL);
    }
  }

  /**
   * 获取报表数据
   *
   * @return Result
   */
  @RequestMapping("/getReportValue")
  public Result getReportValue() {
    try {
      return new Result(true, MessageConstant.GET_REPORT_VALUE_SUCCESS, reportService.getBusinessReport());
    } catch (Exception e) {
      e.printStackTrace();
      return new Result(false, MessageConstant.GET_REPORT_VALUE_FAIL);
    }
  }
}
